<script>
import axios from "../../axios/axiosHelper";
import { Plus, Search, Edit, Delete } from '@element-plus/icons-vue';

export default {
  name: "Book",
  components: {
    Plus,
    Search,
    Edit,
    Delete
  },
  data() {
    return {
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      searchForm: {
        field: '',
        code: ''
      },
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: '',
        press_id: '',
        name: '',
        author: '',
        publish_time: '',
        sale_price: '',
        discount: '',
        category: '',
        stock: 0,
        sales_total: 0,
        user_no: '',
        opera_date: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入图书名称', trigger: 'blur' },
          { min: 2, max: 50, message: '图书名称长度应在2-50个字符之间', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入作者', trigger: 'blur' },
          { min: 2, max: 30, message: '作者名称长度应在2-30个字符之间', trigger: 'blur' }
        ],
        press_id: [
          { required: true, message: '请选择出版社', trigger: 'change' }
        ],
        category: [
          { required: true, message: '请选择图书分类', trigger: 'change' }
        ],
        sale_price: [
          { required: true, message: '请输入售价', trigger: 'blur' },
          { pattern: /^\d+(\.\d{1,2})?$/, message: '售价格式不正确', trigger: 'blur' }
        ],
        discount: [
          { pattern: /^\d+(\.\d{1,2})?$/, message: '折扣格式不正确', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入库存', trigger: 'blur' },
          { pattern: /^\d+$/, message: '库存必须为整数', trigger: 'blur' }
        ],
        publish_time: [
          { required: true, message: '请选择出版时间', trigger: 'change' }
        ]
      },
      pressList: [],
      categoryList: []
    };
  },
  created() {
    // 先获取出版社和分类列表，再获取图书数据
    this.fetchPressList();
    this.fetchCategoryList();
    this.fetchData();
  },
  methods: {
    // 获取图书数据
    fetchData() {
      this.loading = true;
      
      // 确保出版社和分类列表已加载
      const promises = [];
      if (this.pressList.length === 0) {
        promises.push(this.fetchPressList());
      }
      if (this.categoryList.length === 0) {
        promises.push(this.fetchCategoryList());
      }
      
      // 等待出版社和分类列表加载完成后再获取图书数据
      Promise.all(promises).then(() => {
        const params = {
          offset: (this.currentPage - 1) * this.pageSize,
          limit: this.pageSize
        };
        
        // 添加搜索条件
        if (this.searchForm.code) {
          params.code = this.searchForm.code;
        }
        
        return axios.get('/book/list', { params });
      }).then(response => {
        const rows = response.data.rows;
        
        // 处理数据，确保所有需要的字段都存在
        this.tableData = rows.map(row => {
          // 分类名称已经在 row.category 中
          // 查找出版社名称
          const press = this.pressList.find(p => p.id === row.press_id);
          
          return {
            ...row,
            // 确保所有字段都有值，避免表格显示undefined
            category: row.category || '',
            press_name: press ? press.name : '',
            publish_time: row.publish_time || '',
            sale_price: row.sale_price || row.price || '',
            discount: row.discount || '',
            stock: row.stock || 0,
            sales_total: row.sales_total || 0,
            user_no: row.user_no || '',
            opera_date: row.opera_date || ''
          };
        });
        
        this.total = response.data.total;
        this.loading = false;
      }).catch(error => {
        console.error('获取图书数据失败:', error);
        this.$message.error('获取图书数据失败');
        this.loading = false;
      });
    },
    // 获取出版社列表
    fetchPressList() {
      return axios.get('/press/all').then(response => {
        this.pressList = response.data;
        return response.data;
      }).catch(error => {
        console.error('获取出版社列表失败:', error);
        this.$message.error('获取出版社列表失败');
        return [];
      });
    },
    // 获取图书分类列表
    fetchCategoryList() {
      return axios.get('/book-category/all').then(response => {
        this.categoryList = response.data;
        return response.data;
      }).catch(error => {
        console.error('获取图书分类列表失败:', error);
        this.$message.error('获取图书分类列表失败');
        return [];
      });
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchData();
    },
    // 打开添加对话框
    handleAdd() {
      this.dialogTitle = '添加图书';
      this.form = {
        id: '',
        press_id: '',
        name: '',
        author: '',
        publish_time: '',
        sale_price: '',
        discount: '',
        category: '',
        stock: 0,
        sales_total: 0,
        user_no: '',
        opera_date: new Date()
      };
      this.dialogVisible = true;
    },
    // 编辑图书
    handleEdit(index, row) {
      this.dialogTitle = '编辑图书';
      this.form = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    // 提交表单
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          
          // 准备提交的数据
          const formData = {
            ...this.form,
            // 确保日期格式正确
            publish_time: this.form.publish_time || new Date().toISOString().split('T')[0],
            opera_date: this.form.opera_date || new Date().toISOString().replace('T', ' ').split('.')[0],
            // 确保数值类型正确
            stock: Number(this.form.stock),
            sales_total: Number(this.form.sales_total),
            sale_price: Number(this.form.sale_price),
            discount: this.form.discount ? Number(this.form.discount) : null
          };
          
          // 分类已经是字符串，直接使用
          formData.category = this.form.category;
          
          if (this.form.id) {
            // 更新
            axios.put('/book/update', formData).then(response => {
              this.$message.success('更新成功');
              this.dialogVisible = false;
              this.fetchData();
              this.loading = false;
            }).catch(error => {
              console.error('更新图书失败:', error);
              this.$message.error('更新图书失败');
              this.loading = false;
            });
          } else {
            // 添加
            axios.post('/book/add', formData).then(response => {
              this.$message.success('添加成功');
              this.dialogVisible = false;
              this.fetchData();
              this.loading = false;
            }).catch(error => {
              console.error('添加图书失败:', error);
              this.$message.error('添加图书失败');
              this.loading = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    // 删除图书
    handleDelete(index, row) {
      this.$confirm('确认删除该图书?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        axios.delete(`/book/delete/${row.id}`).then(response => {
          this.$message.success('删除成功');
          this.fetchData();
          this.loading = false;
        }).catch(error => {
          console.error('删除图书失败:', error);
          this.$message.error('删除图书失败');
          this.loading = false;
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }
}
</script>

<template>
  <div class="book-container">
    <!-- 标题栏 -->
    <div class="header">
      <div class="title-section">
        <h2 class="page-title">图书管理</h2>
        <el-button type="primary" size="small" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加图书
        </el-button>
      </div>
      <div class="search">
        <el-input v-model="searchForm.code" placeholder="请输入关键词搜索..." clearable size="small" style="width: 250px;">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" size="small" @click="fetchData">搜索</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        v-loading="loading"
        element-loading-text="加载中..."
        :header-cell-style="{backgroundColor: '#f5f7fa', color: '#606266'}"
        highlight-current-row
        stripe
      >
        <el-table-column type="index" min-width="5%" align="center" label="序号"></el-table-column>
        <el-table-column prop="id" label="ID" min-width="5%" align="center"></el-table-column>
        <el-table-column prop="press_name" label="出版社" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="name" label="书名" min-width="12%" align="center"></el-table-column>
        <el-table-column prop="author" label="作者" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="publish_time" label="出版时间" min-width="10%" align="center"></el-table-column>
        <el-table-column prop="sale_price" label="售价" min-width="6%" align="center"></el-table-column>
        <el-table-column prop="discount" label="折扣" min-width="6%" align="center"></el-table-column>
        <el-table-column prop="category" label="分类" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="stock" label="库存" min-width="6%" align="center"></el-table-column>
        <el-table-column prop="sales_total" label="销售总量" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="user_no" label="用户编号" min-width="8%" align="center"></el-table-column>
        <el-table-column prop="opera_date" label="操作日期" min-width="10%" align="center"></el-table-column>
        <el-table-column label="操作" min-width="20%" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-tooltip content="编辑" placement="top" :hide-after="1500">
                <el-button type="primary" circle size="small" @click="handleEdit(scope.$index, scope.row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" :hide-after="1500">
                <el-button type="danger" circle size="small" @click="handleDelete(scope.$index, scope.row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      v-model="dialogVisible" 
      width="550px" 
      :close-on-click-modal="false"
      destroy-on-close
      center
      class="custom-dialog"
    >
      <div class="dialog-content">
        <el-form 
          :model="form" 
          :rules="rules" 
          ref="form" 
          label-width="120px"
          class="book-form"
          status-icon
        >
          <el-form-item label="出版社" prop="press_id">
            <el-select 
              v-model="form.press_id" 
              placeholder="请选择出版社" 
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in pressList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图书名称" prop="name">
            <el-input 
              v-model="form.name" 
              placeholder="请输入图书名称"
              clearable
              maxlength="255"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-input 
              v-model="form.author" 
              placeholder="请输入作者"
              clearable
              maxlength="255"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="出版时间" prop="publish_time">
            <el-date-picker
              v-model="form.publish_time"
              type="date"
              placeholder="选择出版时间"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              clearable
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="售价" prop="sale_price">
            <el-input 
              v-model="form.sale_price" 
              placeholder="请输入售价"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="折扣" prop="discount">
            <el-input 
              v-model="form.discount" 
              placeholder="请输入折扣"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="图书分类" prop="category">
            <el-select 
              v-model="form.category" 
              placeholder="请选择图书分类" 
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="库存" prop="stock">
            <el-input-number 
              v-model="form.stock" 
              :min="0"
              placeholder="请输入库存"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="销售总量" prop="sales_total">
            <el-input-number 
              v-model="form.sales_total" 
              :min="0"
              placeholder="请输入销售总量"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="用户编号" prop="user_no">
            <el-input 
              v-model="form.user_no" 
              placeholder="请输入用户编号"
              clearable
              maxlength="255"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="操作日期" prop="opera_date">
            <el-date-picker
              v-model="form.opera_date"
              type="datetime"
              placeholder="选择操作日期"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
              clearable
            ></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" plain>取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.book-container {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  overflow: auto;
}

.header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
  position: relative;
  padding-left: 12px;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 18px;
  background-color: #409EFF;
  border-radius: 2px;
}

.search {
  display: flex;
  gap: 10px;
  align-items: center;
}

.table-container {
  background-color: #fff;
  border-radius: 6px;
  padding: 10px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  flex: 1;
  overflow: auto;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding-top: 15px;
  border-top: 1px solid #ebeef5;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.custom-dialog :deep(.el-dialog__header) {
  padding: 10px;
  margin: 0;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.custom-dialog :deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 20px 10px;
}

.custom-dialog :deep(.el-dialog__footer) {
  padding: 10px;
  border-top: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.dialog-content {
  max-height: 60vh;
  overflow-y: auto;
}

.book-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-input {
  width: 100%;
}

.el-table {
  margin: 0;
  border-radius: 6px;
  overflow: hidden;
}

.el-table :deep(th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: bold;
  text-align: center;
}

.el-table :deep(td) {
  text-align: center;
}

.el-button--primary {
  background-color: #409EFF;
}

.el-button--success {
  background-color: #67C23A;
}

.el-button--danger {
  background-color: #F56C6C;
}

/* 添加一些动画效果 */
.el-table :deep(tr) {
  transition: background-color 0.3s;
}

.el-table :deep(tr:hover) {
  background-color: #f0f9eb;
}

.el-button {
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
  }
  
  .search {
    width: 100%;
  }
  
  .search .el-input {
    flex: 1;
  }
}
</style>